package com.qingcheng.service.impl;

import com.alibaba.dubbo.config.annotation.Reference;
import com.alibaba.dubbo.config.annotation.Service;
import com.qingcheng.pojo.goods.Category;
import com.qingcheng.pojo.goods.Sku;
import com.qingcheng.pojo.order.OrderItem;
import com.qingcheng.service.goods.CategoryService;
import com.qingcheng.service.goods.SkuService;
import com.qingcheng.service.order.CartService;
import com.qingcheng.service.order.PreferentialService;
import com.qingcheng.util.CacheKey;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;

import java.util.*;
import java.util.stream.Collectors;

/**
 * @author yangjun
 * 2019/7/18
 * 18:52
 */
@Service
public class CartServiceImpl implements CartService {

    @Autowired
    private RedisTemplate redisTemplate;
    @Reference
    private SkuService skuService;
    @Reference
    private CategoryService categoryService;
    @Autowired
    private PreferentialService preferentialService;

    /**
     * 根据用户名获取购物车列表
     *
     * @param username
     * @return
     */
    @Override
    public List<Map<String, Object>> findCartList(String username) {
        System.out.println("从redis提取购物车"+username);
        List<Map<String, Object>> cartList = (List<Map<String, Object>>) redisTemplate.boundHashOps(CacheKey.CART_LIST).get(username);
        if (cartList == null) {
            cartList = new ArrayList<>();
        }

        return cartList;
    }

    /**
     * 添加商品
     *
     * @param username 用户
     * @param skuId    商品id
     * @param num      商品数量
     */
    @Override
    public void addItem(String username, String skuId, Integer num) {
        //遍历购物车,如果购物车中有该商品则增加数量,如果不存在则添加商品
        List<Map<String, Object>> cartLsit = findCartList(username);
        boolean flag = false;//是否购物车中存在
        for (Map map: cartLsit) {
            OrderItem orderItem = (OrderItem)map.get("item");
            if (orderItem.getSkuId().equals(skuId)) {//存在
                if (orderItem.getNum() <= 0) {
                    cartLsit.remove(map);
                    flag = true;
                    break;
                }
                int weight = orderItem.getWeight() / orderItem.getNum();//单个商品重量
                orderItem.setNum(orderItem.getNum() + num);//数量变更
                System.out.println(orderItem.getNum());
                System.out.println(orderItem.getMoney());
                System.out.println(orderItem.getPrice());
                orderItem.setMoney(orderItem.getNum()*orderItem.getPrice());//金额变更
                orderItem.setWeight(weight * orderItem.getNum()); //重量变更
                if (orderItem.getNum() <= 0) {
                    cartLsit.remove(map);
                }
                flag = true;
                break;
            }
        }
        //如果购物车没有该商品,就添加
        if (!flag) {
            Sku sku = skuService.findById(skuId);
            if (sku == null) {
                throw new RuntimeException("商品不存在");
            }
            if (!"1".equals(sku.getStatus())) {
                throw new RuntimeException("商品状态不合法");
            }
            if (num < 0) {
                throw new RuntimeException("商品数量不合法");
            }
            OrderItem orderItem = new OrderItem();


            orderItem.setSkuId(skuId);
            orderItem.setSpuId(sku.getSpuId());
            orderItem.setNum(num);
            orderItem.setImage(sku.getImage());
            orderItem.setPrice(sku.getPrice());
            orderItem.setName(sku.getName());
            orderItem.setMoney(sku.getPrice()*num);
            if (sku.getWeight() == null) {
                sku.setWeight(0);
            }
            orderItem.setWeight(sku.getWeight() * num);//重量计算\
            //商品分类
            orderItem.setCategoryId3(sku.getCategoryId());
            Category category3 = (Category) redisTemplate.boundHashOps(CacheKey.CATEGORY).get(sku.getCategoryId());
            if (category3 == null) {
                category3 = categoryService.findById(sku.getCategoryId());
                redisTemplate.boundHashOps(CacheKey.CATEGORY).put(sku.getCategoryId(), category3);
            }
            orderItem.setCategoryId2(category3.getParentId());
            Category category2 = (Category) redisTemplate.boundHashOps(CacheKey.CATEGORY).get(category3.getParentId());
            if (category2 == null) {
                category2 = categoryService.findById(category3.getParentId());
                redisTemplate.boundHashOps(CacheKey.CATEGORY).put(category3.getParentId(), category2);
            }
            orderItem.setCategoryId1(category2.getParentId());
            Map map = new HashMap();
            map.put("item", orderItem);
            map.put("checked", true);//默认选中
            cartLsit.add(map);
        }
        redisTemplate.boundHashOps(CacheKey.CART_LIST).put(username, cartLsit);
    }

    /**
     * 修改商品选中状态
     *
     * @param username
     * @param skuId
     * @param checked
     * @return
     */
    @Override
    public boolean updateChecked(String username, String skuId, boolean checked) {
        List<Map<String, Object>> cartLsit = findCartList(username);
        boolean isok = false;
        for (Map<String, Object> map : cartLsit) {
            OrderItem orderItem = (OrderItem) map.get("item");
            if (skuId.equals(orderItem.getSkuId())) {
                map.put("checked", checked);
                isok = true;
                break;
            }
        }
        if (isok = true) {
            redisTemplate.boundHashOps(CacheKey.CART_LIST).put(username, cartLsit);
        }
        return isok;
    }

    /**
     * 删除选中购物车
     *
     * @param username
     */
    @Override
    public void deleteCheckedCart(String username) {
        //获取未选中购物车
        List<Map<String, Object>> cartLsit = findCartList(username).stream()
                .filter(cart -> (boolean) cart.get("checked") == false)
                .collect(Collectors.toList());
        redisTemplate.boundHashOps(CacheKey.CART_LIST).put(username,cartLsit);

    }

    /**
     * 根据当前用户计算优惠金额
     * @param username 当前用户
     * @return 优惠金额
     */
    @Override
    public int preferential(String username) {
        //获取选中的购物车 List<OrderItem> List<Map>
        List<OrderItem> orderItemList = findCartList(username).stream()
                .filter(cart -> (boolean) cart.get("checked") == true)
                .map(cart -> (OrderItem) cart.get("item")).collect(Collectors.toList());
        //按分类聚合统计每个分类的金额 group by
        Map<Integer, IntSummaryStatistics> carMap = orderItemList.stream()
                .collect(Collectors.groupingBy(OrderItem::getCategoryId3,
                        Collectors.summarizingInt(OrderItem::getMoney)));
        //循环结果，统计每个分类的优惠金额，并累加
        int allPreMoney=0;//累计优惠金额
        for (Integer categoryId : carMap.keySet()) {
            // 获取品类的消费金额
            int money = (int) carMap.get(categoryId).getSum();
            int preMoney = preferentialService.findPreMoneyByCategoryId(categoryId, money);
            System.out.println("分类："+categoryId+" 消费金额："+ money+ " 优惠金额：" + preMoney);
            allPreMoney+=preMoney;

        }
        return allPreMoney;
    }

    /**
     * 获取最新的用户购物车列表
     * @param username 当前用户
     * @return
     */
    @Override
    public List<Map<String, Object>> findNewOrderItemList(String username) {
        //获取当前购物车列表
        List<Map<String, Object>> cartLsit = findCartList(username);
        //循环购物车列表，重新读取每个商品的最新价格
        for (Map<String, Object> cart : cartLsit) {
            OrderItem orderItem = (OrderItem) cart.get("item");
            Sku sku = skuService.findById(orderItem.getSkuId());
            orderItem.setPrice(sku.getPrice());//更新价格
            orderItem.setMoney(sku.getPrice()*orderItem.getNum());//更新总金额
        }
        redisTemplate.boundHashOps(CacheKey.CART_LIST).put(username,cartLsit);
        return cartLsit;
    }

}
